<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable no-dupe-keys -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-destroyed-lifecycle -->
<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="6" v-for="(card, index) in dataCards" :key="index">
        <el-card class="data-card" :body-style="{ padding: '20px' }">
          <div class="card-header">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-icon" :style="{ backgroundColor: card.backgroundColor }">
              <i :class="card.icon"></i>
            </div>
          </div>
          <div class="card-number">{{ card.count }}</div>
          <div class="card-footer">
            <span>
              <i class="el-icon-top" v-if="card.rate > 0"></i>
              <i class="el-icon-bottom" v-else></i>
              {{ Math.abs(card.rate) }}%
            </span>
            <span>较上周</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>用户注册趋势</span>
            <el-radio-group v-model="chartPeriod" size="small" style="float: right">
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="year">年</el-radio-button>
            </el-radio-group>
          </div>
          <div id="user-trend-chart" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>用户分布</span>
          </div>
          <div id="user-distribution-chart" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="system-card">
          <div slot="header" class="clearfix">
            <span>系统消息</span>
            <el-button style="float: right; padding: 3px 0" type="text">查看全部</el-button>
          </div>
          <div class="message-list">
            <div v-for="(msg, index) in systemMessages" :key="index" class="message-item">
              <div class="message-icon" :class="getMessageIconClass(msg.type)">
                <i :class="getMessageIconType(msg.type)"></i>
              </div>
              <div class="message-content">
                <div class="message-title">{{ msg.title }}</div>
                <div class="message-time">{{ msg.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="quick-card">
          <div slot="header" class="clearfix">
            <span>快捷入口</span>
          </div>
          <div class="quick-list">
            <el-row :gutter="20">
              <el-col :span="8" v-for="(item, index) in quickEntries" :key="index">
                <div class="quick-item" @click="handleQuickEntry(item.path)">
                  <i :class="item.icon"></i>
                  <span>{{ item.title }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 引入API
import { dashboardAPI } from '@/api/api';
// 引入图表
import * as echarts from 'echarts';

export default {
  name: 'DashboardView',
  data() {
    return {
      // 数据卡片
      dataCards: [],
      // 图表周期
      chartPeriod: 'week',
      // 用户注册趋势数据
      registrationStats: [],
      // 用户分布数据
      userDistribution: [],
      // 系统消息
      systemMessages: [],
      // 快捷入口
      quickEntries: [
        { title: '用户管理', icon: 'el-icon-user', path: '/admin/user-management' },
        { title: '产品管理', icon: 'el-icon-goods', path: '/admin/product-management' },
        { title: '订单管理', icon: 'el-icon-s-order', path: '/admin/order-management' },
        { title: '农户管理', icon: 'el-icon-s-home', path: '/admin/farmer-management' },
        { title: '经销商管理', icon: 'el-icon-truck', path: '/admin/dealer-management' },
        { title: '溯源管理', icon: 'el-icon-search', path: '/admin/trace-management' }
      ],
      // 图表实例
      trendChart: null,
      distributionChart: null
    }
  },
  watch: {
    chartPeriod: {
      handler() {
        this.fetchRegistrationStats();
      }
    }
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    // 获取所有数据
    async fetchData() {
      this.fetchDataCards();
      this.fetchUserDistribution();
      this.fetchRegistrationStats();
      this.fetchSystemMessages();
    },
    
    // 获取数据卡片数据
    async fetchDataCards() {
      try {
        const response = await dashboardAPI.getDataCards();
        console.log('数据卡片信息:', response.data); // 调试用
        
        // 检查返回的数据格式
        if (response.data) {
          // 转换为前端需要的格式
          this.dataCards = [
            {
              title: '总用户数',
              count: response.data.totalUsers || 0,
              rate: 5.6,
              icon: 'el-icon-user',
              backgroundColor: '#409EFF'
            },
            {
              title: '总产品数',
              count: response.data.totalProducts || 0,
              rate: 3.2,
              icon: 'el-icon-s-goods',
              backgroundColor: '#67C23A'
            },
            {
              title: '今日新增用户',
              count: response.data.todayNewUsers || 0,
              rate: 8.1,
              icon: 'el-icon-user-solid',
              backgroundColor: '#E6A23C'
            },
            {
              title: '今日新增产品',
              count: response.data.todayNewProducts || 0,
              rate: -2.5,
              icon: 'el-icon-s-promotion',
              backgroundColor: '#F56C6C'
            }
          ];
        } else {
          console.error('数据卡片信息格式不符合预期:', response.data);
          // 设置默认数据
          this.dataCards = [
            {
              title: '总用户数',
              count: 0,
              rate: 0,
              icon: 'el-icon-user',
              backgroundColor: '#409EFF'
            },
            {
              title: '总产品数',
              count: 0,
              rate: 0,
              icon: 'el-icon-s-goods',
              backgroundColor: '#67C23A'
            },
            {
              title: '今日新增用户',
              count: 0,
              rate: 0,
              icon: 'el-icon-user-solid',
              backgroundColor: '#E6A23C'
            },
            {
              title: '今日新增产品',
              count: 0,
              rate: 0,
              icon: 'el-icon-s-promotion',
              backgroundColor: '#F56C6C'
            }
          ];
        }
      } catch (error) {
        console.error('Failed to fetch data cards:', error);
        this.$message.error('获取数据卡片信息失败');
        // 设置默认数据
        this.dataCards = [
          {
            title: '总用户数',
            count: 0,
            rate: 0,
            icon: 'el-icon-user',
            backgroundColor: '#409EFF'
          },
          {
            title: '总产品数',
            count: 0,
            rate: 0,
            icon: 'el-icon-s-goods',
            backgroundColor: '#67C23A'
          },
          {
            title: '今日新增用户',
            count: 0,
            rate: 0,
            icon: 'el-icon-user-solid',
            backgroundColor: '#E6A23C'
          },
          {
            title: '今日新增产品',
            count: 0,
            rate: 0,
            icon: 'el-icon-s-promotion',
            backgroundColor: '#F56C6C'
          }
        ];
      }
    },
    
    // 获取用户分布数据
    async fetchUserDistribution() {
      try {
        const response = await dashboardAPI.getUserDistribution();
        console.log('用户分布数据:', response.data); // 调试用
        
        // 确保接收到正确格式的数据
        if (response.data && response.data.roles) {
          this.userDistribution = response.data;
        } else {
          console.error('用户分布数据格式不符合预期:', response.data);
          // 设置默认数据，避免渲染错误
          this.userDistribution = { roles: [] };
        }
        
        this.$nextTick(() => {
          this.initDistributionChart();
        });
      } catch (error) {
        console.error('Failed to fetch user distribution:', error);
        this.$message.error('获取用户分布数据失败');
        // 设置默认数据，避免渲染错误
        this.userDistribution = { roles: [] };
      }
    },
    
    // 获取用户注册趋势数据
    async fetchRegistrationStats() {
      try {
        const response = await dashboardAPI.getRegistrationStats(this.chartPeriod);
        console.log('注册统计数据:', response.data); // 调试用
        
        // 检查数据格式并进行适当处理
        if (response.data && Array.isArray(response.data)) {
          // 如果直接返回数组
          this.registrationStats = response.data;
        } else if (response.data && response.data.lastThirtyDays) {
          // 如果是包含lastThirtyDays字段的对象
          // 转换成趋势图需要的数据格式
          this.registrationStats = Object.entries(response.data.lastThirtyDays).map(([date, count]) => ({
            date: date,
            registrationCount: count,
            activeCount: Math.round(count * 0.8) // 模拟活跃用户数据，实际应从后端获取
          }));
        } else {
          // 默认为空数组
          console.error('注册统计数据格式不符合预期:', response.data);
          this.registrationStats = [];
        }
        
        this.$nextTick(() => {
          this.initTrendChart();
        });
      } catch (error) {
        console.error('Failed to fetch registration stats:', error);
        this.$message.error('获取用户注册趋势数据失败');
        this.registrationStats = []; // 确保出错时也设置为数组
      }
    },
    
    // 获取系统消息
    async fetchSystemMessages() {
      try {
        const response = await dashboardAPI.getSystemMessages();
        if (response.data && response.data.messages) {
          this.systemMessages = response.data.messages.map(msg => ({
            ...msg,
            time: msg.timestamp || new Date().toISOString() // 确保使用timestamp字段或提供默认值
          }));
        } else {
          this.systemMessages = [];
          console.error('系统消息数据格式不符合预期:', response.data);
        }
      } catch (error) {
        console.error('Failed to fetch system messages:', error);
        this.$message.error('获取系统消息失败');
        this.systemMessages = [];
      }
    },
    
    // 初始化用户趋势图表
    initTrendChart() {
      if (this.trendChart != null && this.trendChart != "" && this.trendChart != undefined) {
        this.trendChart.dispose();
      }
      
      this.trendChart = echarts.init(document.getElementById('user-trend-chart'));
      
      // 确保registrationStats是数组且不为空
      if (!Array.isArray(this.registrationStats) || this.registrationStats.length === 0) {
        console.warn('注册数据不可用，显示空图表');
        // 设置空图表
        this.trendChart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center'
          }
        });
        return;
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['注册用户', '活跃用户']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.registrationStats.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '注册用户',
            type: 'line',
            stack: 'Total',
            data: this.registrationStats.map(item => item.registrationCount),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.7)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.1)'
                }
              ])
            }
          },
          {
            name: '活跃用户',
            type: 'line',
            stack: 'Total',
            data: this.registrationStats.map(item => item.activeCount),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#67C23A'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(103, 194, 58, 0.7)'
                },
                {
                  offset: 1,
                  color: 'rgba(103, 194, 58, 0.1)'
                }
              ])
            }
          }
        ]
      };
      
      this.trendChart.setOption(option);
      
      window.addEventListener('resize', () => {
        this.trendChart.resize();
      });
    },
    
    // 初始化用户分布图表
    initDistributionChart() {
      if (this.distributionChart != null && this.distributionChart != "" && this.distributionChart != undefined) {
        this.distributionChart.dispose();
      }
      
      this.distributionChart = echarts.init(document.getElementById('user-distribution-chart'));
      
      // 确保userDistribution.roles存在
      const roles = this.userDistribution.roles || [];
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: roles.map(item => item.role)
        },
        series: [
          {
            name: '用户分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: roles.map(item => ({
              value: item.count,
              name: item.role
            }))
          }
        ]
      };
      
      this.distributionChart.setOption(option);
      
      window.addEventListener('resize', () => {
        this.distributionChart.resize();
      });
    },
    
    // 获取消息图标样式
    getMessageIconClass(type) {
      switch (type) {
        case 'success':
          return 'success-icon';
        case 'warning':
          return 'warning-icon';
        case 'info':
          return 'info-icon';
        case 'error':
          return 'error-icon';
        default:
          return 'info-icon';
      }
    },
    
    // 获取消息图标类型
    getMessageIconType(type) {
      switch (type) {
        case 'success':
          return 'el-icon-success';
        case 'warning':
          return 'el-icon-warning';
        case 'info':
          return 'el-icon-info';
        case 'error':
          return 'el-icon-error';
        default:
          return 'el-icon-info';
      }
    },
    
    // 处理快捷入口点击
    handleQuickEntry(path) {
      this.$router.push(path);
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.distributionChart) {
      this.distributionChart.dispose();
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
  height: 150px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  color: #303133;
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.card-icon i {
  font-size: 24px;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.card-footer {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 5px;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.system-card, .quick-card {
  height: 375px;
  margin-bottom: 20px;
}

.message-list {
  height: 310px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px solid #EBEEF5;
}

.message-item:last-child {
  border-bottom: none;
}

.message-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.success-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.warning-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.info-icon {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.error-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.message-content {
  flex: 1;
}

.message-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.quick-list {
  display: flex;
  flex-wrap: wrap;
}

.quick-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  border-radius: 6px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-item i {
  font-size: 30px;
  color: #409EFF;
  margin-bottom: 10px;
}

.quick-item span {
  font-size: 14px;
  color: #303133;
}
</style>
